package com.ssmTest.service.impl;

import com.ssmTest.dao.IUserDao;
import com.ssmTest.model.SystemSetup;
import com.ssmTest.model.User;
import com.ssmTest.service.*;
import com.ssmTest.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Random;

@Service("userService")
public class UserServiceImpl implements IUserService {
    @Resource
    private IUserDao userDao;

    @Autowired
    private IUserService userService;

    @Autowired
    private ISystemSetupService iSystemSetupService;
    @Autowired
    private FileService fileService;
    @Autowired
    private DateTimeService dateTimeService;


    @Autowired
    private IVerificationCodeService verificationCodeService;

    public User selectUser(int id) {
        return this.userDao.selectUser(id);
    }

    public User selectUserPhone(String phone) {
        return this.userDao.selectUserPhone(phone);
    }

    //用户登录


    public int userLogin(String phone_number, String passwd, ModelMap modelMap) {
        User user = userService.selectUserPhone(phone_number);
        if (user != null && passwd.equals(user.getPasswd())) {
            if (user.getCustomer_type() == -1) {
                System.out.println(user.getCustomer_type());
                return 0;
            }
            return 1;
        } else if (user == null) {
            return 3;
        } else {
            return 2;
        }
    }

    public int userLogins(HttpSession session, String phone_number, String passwd, ModelMap modelMap) {
        User user = userService.selectUserPhone(phone_number);
        if (user != null && passwd.equals(user.getPasswd())) {
            if (user.getCustomer_type() == -1) {
                System.out.println(user.getCustomer_type());
                return 0;
            }
            session.setAttribute("id", user.getId());
            session.setAttribute("phone", user.getPhone_number());
            return 1;
        } else if (user == null) {
            return 3;
        } else {
            return 2;
        }
    }
    //用户注册

    /**
     * 传入参数：
     * 电话号码,密码，验证码，邀请码（没有为空字符串），用户类型（int）
     * <p>
     * 返回值：
     * 1 注册成功
     * -1 用户重复或已存在
     * -2 验证码失效
     */
    public int userRegister(String phone_number, String passwd, String invitation_code, int customer_type) {
        //用户查重
        if (userService.user_Check(phone_number))
            //出现重复
            return -1;

        //验证正确开始注册
        User user = new User();
        user.setPhone_number(phone_number);
        user.setPasswd(passwd);
        user.setInvitation_code(invitation_code);
        user.setCustomer_type(customer_type);
        user.setState(0);
        user.setTime(dateTimeService.getTime());
        if (customer_type == 2) {
            user.setRoyalty(iSystemSetupService.getSystem().getRoyalty_of_user());
            //生成六位随机邀请码区分大小写
            String a = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
            String rands = "";
            for (int i = 0; i < 6; i++) {
                int rand = (int) (Math.random() * a.length());
                rands += a.charAt(rand);
            }
            while (userService.selectInvitCode(rands) != null) {
                rands = "";
                for (int i = 0; i < 6; i++) {
                    int rand = (int) (Math.random() * a.length());
                    rands += a.charAt(rand);
                }
            }
            user.setInvitation_code(rands);
        }
        userService.insertUser(user);
        return 1;
    }

    //用户查重
    public boolean user_Check(String phone) {
        if (userService.selectUserPhone(phone) != null)
            return false;
        return true;
    }

    //个人信息完善
    //个人信息完善
    public int informationPerfection(int id, MultipartFile group_photo, int gender, String work_year, String drving_license, String payment, String address, String planting_type) {
        User user = userService.selectUser(id);
        String load;
        if (user == null)
            return 0;
        if (group_photo != null) {
            load = "";
            user.setGroup_photo(load + " " + fileService.uploadFile(group_photo, "groupphoto" + id));
        }
        if (gender != 0)
            user.setGender(gender);
        if (!StringUtils.isEmpty(work_year))
            user.setWork_years(work_year);
        if (!StringUtils.isEmpty(drving_license))
            user.setDriving_license(drving_license);
        if (!StringUtils.isEmpty(payment))
            user.setPayment(payment);
        if (!StringUtils.isEmpty(address))
            user.setAddress(address);
        if (!StringUtils.isEmpty(planting_type))
            user.setPlanting_type(planting_type);
        userService.updateUser(user);
        return 1;
    }

    //个人信息修改
    public void informationModification(String group_photo, String work_year, String drving_license, String payment, String address) {
//        User user = userService.selectUserPhone(session.getAttribute("phone_number").toString());
//        user.setGroup_photo(group_photo);
//        user.setWork_years(work_year);
//        user.setDriving_license(drving_license);
//        user.setPayment(payment);
//        user.setAddress(address);
//        userService.updateUser(user);
    }

    //更改用户状态
    public void userAudit(String phone, int state) {
        User user = userService.selectUserPhone(phone);
        user.setState(state);
        userService.updateUserState(user);
    }

    public boolean checkPw(String username, String passwd) {
        if (userService.selectUserPhone(username).getPasswd().equals(passwd))
            return true;
        return false;
    }

    //-1用户不存在  0旧密码错误 1修改密码成功
    public int changePw(String username, String oldPasswd, String passwd) {
        User user = userService.selectUserPhone(username);
        if (user == null)
            return -1;
        if (!checkPw(username, oldPasswd))
            return 0;
        user.setPasswd(passwd);
        this.userDao.updatePasswd(user);
        return 1;
    }

    public void insertUser(User user) {
        this.userDao.insertUser(user);
    }

    public void updateUser(User user) {
        this.userDao.updateUser(user);
    }

    public void updateUserState(User user) {
        this.userDao.updateUserState(user);
    }

    public List<User> selectByState(int state) {
        List<User> list = userDao.selectUserByState(state);
        return list;
    }

    public List<User> selectByStates() {
        List<User> list = userDao.selectUserByStates();
        return list;
    }

    public void updateFailReasion(User user) {
        this.userDao.updateUserFailReasion(user);
    }

    public int numberOfUser(int state) {
        return this.userDao.numberOfUser(state);
    }

    public int numberOfUser(String startdate, String enddate) {
        return this.userDao.numberOfUsers(startdate, enddate);
    }

    //实名认证
    public int updateIDCard(int id, String id_card, String id_number) {
        if (userService.selectUser(id) == null)
            return 0;
        userDao.updateIDCard(id, id_card, id_number);
        return 1;
    }

    //更新门户
    public int updateGateway(int id, String gateway) {
        if (userService.selectUser(id) == null)
            return 0;
        userDao.updateGateway(id, gateway);
        return 1;
    }

    public int updateLicense(int id, String license) {
        if (userService.selectUser(id) == null)
            return 0;
        userDao.updateLicense(id, license);
        return 1;
    }

    public List<User> selectUserByInvitCode(String invitation_code) {
        return userDao.selectUserByInvitCode(invitation_code);
    }

    public User selectInvitCode(String invitation_code) {
        return userDao.selectInvitCode(invitation_code);
    }
}
